# coding-UTF-8
import os
import uuid
import numpy as np
from PIL import Image,ImageFile

# 垂直翻转
# 传入参数的同时，指定好数据类型
def vflip(image_path: str,output_dir: str):
    ext = _check_format(image_path)
    result = os.path.join(output_dir,'{}.{}'.format(uuid.uuid4(),ext))
    im = Image.open(image_path).convert('RGB') # 打开图像并转换为RGB模式
    im_array = np.array(im)
    flipped_im_array = np.flipud(im_array)
    flipped_im = Image.fromarray(flipped_im_array)
    if flipped_im.mode != 'RGB':
        flipped_im = flipped_im.convert('RGB') # 确保图像为RGB模式
    flipped_im.save(result)

# 水平翻转
# 传入参数的同时，指定好数据类型
def  hflip(image_path: str,output_dir: str):
    ext = _check_format(image_path)
    result = os.path.join(output_dir,'{}.{}'.format(uuid.uuid4(),ext))
    im = Image.open(image_path).convert('RGB') # 打开图像设置为rgb格式
    im_array = np.array(im)
    flipped_im_array = np.fliplr(im_array) # 一定要调用numpy的水平翻转的方法fliplr
    flipped_im = Image.fromarray(flipped_im_array)
    if flipped_im.mode != 'RGB':
        flipped_im = flipped_im.convert('RGB')
    flipped_im.save(result)

# 翻转
def rotate(image_path: str,output_dir: str,angle: int):
    ext = _check_format(image_path)
    result = os.path.join(output_dir,'{}.{}'.format(uuid.uuid4(),ext))
    im = Image.open(image_path)
    rotated_im = im.rotate(angle)
    rotated_im.save(result)

# 转置
"""
type：0 逆时针旋转90度，对称翻转
type：1 顺时针旋转90度
type：2 逆时针旋转90度
type：3 顺时针旋转90度，对称翻转
"""
def transpose(image_path: str,output_dir: str,trans_type: int):
    ext = _check_format(image_path)
    result = os.path.join(output_dir,'{}.{}'.format(uuid.uuid4(),ext))
    im = Image.open(image_path).convert('RGB')
    # 这些参数需要手动重新编写一遍
    transpose_im = None
    if trans_type == 0:
        transpose_im = im.transpose(method=Image.TRANSPOSE)
    elif trans_type == 1:
        transpose_im = im.rotate(270,expand=True) # 使用替代转置，因为通常没有270的转置
    elif trans_type == 2:
        transpose_im = im.rotate(90,expand=True)
    elif trans_type == 3:
        transpose_im = im.transpose(method=Image.TRANSPOSE)
    if transpose_im.mode != 'RGB':
        transpose_im = transpose_im.convert('RGB')
    transpose_im.save(result)

# 检查图片路径格式
def _check_format(image_path: str):
    ext = os.path.basename(image_path).strip().split('.')[-1]
    # 例如：image.jpg将点后切掉只保留image
    if ext not in ['png','ipg','jpeg']:
        raise Exception('format error')
    return ext

if __name__ == '__main__':
    print(transpose())





